package com.pine.dbant.plugin.sqlite.function;

import com.pine.dbant.common.jdbc.JdbcUtils;
import com.pine.dbant.common.model.EditorDbKey;
import com.pine.dbant.common.plugin.meta.JdbcMetadataAnalysisConfig;
import com.pine.dbant.common.plugin.meta.QueryMetadataParam;
import com.pine.dbant.common.plugin.meta.function.jdbc.AllMetadataEditorKeyFunction;
import com.pine.sunflower.core.utils.Strings;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author xiaoyuan
 * @create 2023/3/15 15:20
 **/
public class SqliteAllMetadataEditorKeyFunction extends AllMetadataEditorKeyFunction {


    public SqliteAllMetadataEditorKeyFunction(String type) {
        super(type);
    }


    @Override
    public List<EditorDbKey> doQuery(JdbcMetadataAnalysisConfig metadataAnalysisConfig, QueryMetadataParam queryMetadataParam) {
        String allCatalogSql = "PRAGMA database_list";
        List<Map<String, Object>>  catalogResult = JdbcUtils.getSqlRunner(metadataAnalysisConfig.getConnection()).queryList(allCatalogSql);
        String allTablesSql;
        List<Map<String, Object>> tableResult ;
        EditorDbKey editorDbKey = new EditorDbKey();
        List<EditorDbKey> result = new ArrayList<>();
        String name;
        Object nameObject;
        for(Map<String,Object> catalogMap:catalogResult ){
            nameObject =   catalogMap.get("name");
            if(nameObject!=null){
                editorDbKey = new EditorDbKey();
                editorDbKey.setDbName(String.valueOf(nameObject));
                allTablesSql = Strings.format("PRAGMA {}.table_list",editorDbKey.getDbName());
                tableResult = JdbcUtils.getSqlRunner(metadataAnalysisConfig.getConnection()).queryList(allTablesSql);
                editorDbKey.setTables(tableResult.stream().map(e -> {
                    EditorDbKey.Table table = new EditorDbKey.Table();
                    table.setType((String) e.get("type"));
                    table.setTblName((String) e.get("name"));
                    return table;
                }).collect(Collectors.toList()));
                result.add(editorDbKey);
            }
        }

        return result;
    }
}
